<template>
  <div class="hello">
    <!-- <div class="preview" @click="showData" v-html="msg" /> -->
    <!-- 你不需要担心一个页面中过多vue-ueditor-wrap组件会导致混乱,或者重复引用JS(打开控制台瞄一眼),每个组件都保证拥有一个独立的UEditor实例,你可以尝试把数字改成99(根据自己电脑自行斟酌),但依然稳定可用 -->
    <vue-ueditor-wrap
      ref="ueditor"
      :key="flagId"
      v-model="msg"
      :destroy="true"
      :config="config"
      @ready="ready"
      @beforeInit="addCustomUI"
    />

    <!-- 上传文件 -->
    <input
      :id="flagId + 1"
      ref="inputer"
      type="file"
      name="file"
      style="display:none"
      @change="handleFileChange"
      @touchstart="handleFileChange"
    >

    <el-dialog title="上传视频" :visible.sync="uploadVideo">
      <div style="line-height: 1; margin-bottom: 20px;">
        <el-alert
          title="请先上传视频封面图片"
          type="info"
          description="封面图片仅支持jpg/png格式，视频暂时仅支持mp4格式"
          show-icon
          :closable="false"
        />
      </div>
      <upload :data="imgData" />
      <div slot="footer" class="dialog-footer">
        <el-button :loading="uploading" @click="uploadVideo = false">取 消</el-button>
        <el-button
          :loading="uploading"
          type="primary"
          :disabled="!imgData.imgUrl"
          @click="uploadfile"
        >上传视频</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 1、引入VueUeditorWrap组件
import VueUeditorWrap from 'vue-ueditor-wrap' // ES6 Module
// const VueUeditorWrap = require('vue-ueditor-wrap') // CommonJS
import { uploadFile } from 'api/common'

import Upload from 'components/Upload/img-upload'

export default {
  name: 'HelloWorld',
  // 2、注册组件
  components: {
    VueUeditorWrap,
    Upload
  },
  data() {
    return {
      flagId: this.$route.query.id || 1,
      msg: '',
      // 4、根据项目需求自行配置,具体配置参见ueditor.config.js源码或 http://fex.baidu.com/ueditor/#start-start
      config: {
        // 编辑器不自动被内容撑高
        autoHeightEnabled: true,
        // 初始容器高度
        initialFrameHeight: 240,
        // 初始容器宽度
        initialFrameWidth: '90%',
        // 上传文件接口（这个地址是我为了方便各位体验文件上传功能搭建的临时接口，请勿在生产环境使用！！！）
        // serverUrl: 'http://tmall.baomeitmall.com/mall/upload',
        // UEditor 资源文件的存放路径，如果你使用的是 vue-cli 生成的项目，通常不需要设置该选项，vue-ueditor-wrap 会自动处理常见的情况，如果需要特殊配置，参考下方的常见问题2
        UEDITOR_HOME_URL: 'static/UEditor/',
        // 配合最新编译的资源文件，你可以实现添加自定义Request Headers,详情https://github.com/HaoChuan9421/ueditor/commits/dev-1.4.3.3
        // headers: {
        //   access_token: '37e7c9e3fda54cca94b8c88a4b5ddbf3'
        // }
        toolbars: [
          ['source', '|', 'undo', 'redo'],
          ['bold', 'italic', 'underline', 'fontborder', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|',
            'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
            'rowspacingtop', 'rowspacingbottom', 'lineheight'],
          ['customstyle', 'paragraph', 'fontsize', '|',
            'directionalityltr', 'directionalityrtl', 'indent', '|',
            'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|',
            'touppercase', 'tolowercase', '|', 'pagebreak', 'template', 'background', 'horizontal', '|'
          ]]
      },
      form: {
        file: null,
        path: 'home'
      },

      imgData: {
        myId: Math.random(),
        path: 'news',
        imgUrl: '',
        ImgSize: 10000,
        text: '视频封面图片大小不得超过300k'
      },

      uploadVideo: false,
      uploading: false
    }
  },
  mounted() {
  },
  methods: {
    ready(editorInstance) {
      console.log(`实例${editorInstance.key}已经初始化:`, editorInstance)
    },
    // 设置编辑器内容
    edit(data) {
      this.msg = data
    },
    showData() {
      alert(this.msg)
    },

    // 将编辑器内的内容传到父组件
    onEditorChange() {
      return this.msg
    },
    addCustomUI(editorId, editorConfig) {
      console.log('----editorId---', editorId)
      const _this = this
      // 图片上传
      window.UE.registerUI('img-upload-button' + editorId, function(editor, uiName) {
        editor.registerCommand(uiName, {
          execCommand: function() {
            _this.uploadfile()
          }
        })
        var btn = new window.UE.ui.Button({
          name: uiName,
          title: '上传图片',
          cssRules: "background-image: url('static/img/img-icon.png') !important;background-size: cover;",
          onclick: function() {
            editor.execCommand(uiName)
          }
        })
        editor.addListener('selectionchange', function() {
          var state = editor.queryCommandState(uiName)
          if (state === -1) {
            btn.setDisabled(true)
            btn.setChecked(false)
          } else {
            btn.setDisabled(false)
            btn.setChecked(state)
          }
        })
        return btn
      })

      // 视频上传
      window.UE.registerUI('video-upload-button' + editorId, function(editor, uiName) {
        editor.registerCommand(uiName, {
          execCommand: function() {
            // _this.uploadfile()
            _this.uploadVideo = true
          }
        })
        var btn = new window.UE.ui.Button({
          name: uiName,
          // 提示
          title: '上传视频',
          cssRules: "background-image: url('static/img/video-icon.png') !important;background-size: cover",
          onclick: function() {
            editor.execCommand(uiName)
          }
        })
        editor.addListener('selectionchange', function() {
          var state = editor.queryCommandState(uiName)
          if (state === -1) {
            btn.setDisabled(true)
            btn.setChecked(false)
          } else {
            btn.setDisabled(false)
            btn.setChecked(state)
          }
        })
        return btn
      })
    },

    // 上传文件 图片/视频
    handleFileChange() {
      if (this.uploading) {
        return
      }
      const inputDOM = this.$refs.inputer
      const file = inputDOM.files[0]
      // 判断是否是图片上传
      const imageType = /image.*/
      const isImage = file.type.match(imageType)
      this.checkImg(file, isImage).then((imgInfo) => {
        this.uploading = true
        const formData = new window.FormData()
        Object.keys(this.form).forEach((y) => {
          formData.append(y, this.form[y])
        })
        formData.append('file', file)
        uploadFile(formData).then((re) => {
          this.uploading = false
          const { data } = re
          console.log('data', data)
          this.setFileHtml(isImage, data, imgInfo)
        })
        this.$refs.inputer.value = ''
      })
    },

    // 获取上传图片宽高
    checkImg(file, isImage) {
      return new Promise((resolve, reject) => {
        if (isImage && !this.uploadVideo) {
          const reader = new window.FileReader()
          reader.onload = () => {
            const image = new window.Image()
            image.src = reader.result
            image.onload = () => {
              const sizeInfo = {}
              sizeInfo.width = image.width
              sizeInfo.height = image.height
              resolve(sizeInfo)
            }
          }
          reader.readAsDataURL(file)
        } else if (file.type.includes('video')) {
          const isMP4 = file.type === 'video/mp4'
          if (!isMP4) {
            this.$alert('图片的格式暂时仅支持mp4格式哦～', '提示', {
              confirmButtonText: '确认',
              type: 'warning'
            })
            return
          }
          resolve({
            width: '',
            height: ''
          })
        } else {
          this.$alert('请上传正确格式的文件', '提示', {
            confirmButtonText: '确认',
            type: 'warning'
          })
          reject()
        }
      })
    },

    setFileHtml(isImage, data, imgInfo) {
      console.log(isImage, data, imgInfo, '----')
      if (isImage) {
        const mainPath = `${data}${data.indexOf('?') !== -1 ? '&' : '?'}w=${imgInfo.width}&h=${imgInfo.height}`
        const inHtml = `<img class="wscnph" style="max-width: 100%;height: auto;" src="${mainPath}" width="${imgInfo.width}" height="${imgInfo.height}">`
        this.$refs.ueditor.editor.execCommand('inserthtml', inHtml)
      } else {
        if (!this.uploadVideo) {
          this.imgData.imgUrl = ''
          return
        }
        const fileUrl = data
        const inHtml = `<div>
                  <p style="padding-bottom: 10px;" />
                  <p>
                    <video
                      controls
                      x5-playsinline playsinline webkit-playsinline
                      poster="/${this.imgData.imgUrl}"
                      style="width: 100%;height: auto;
                      object-fit: fill" >
                        <source src="${fileUrl}" type="video/mp4" />
  		                  您的浏览器不支持video标签播放视频
                    </video>
                  </p>
                </div>
                <p style="padding-bottom: 10px;" />`
        this.$refs.ueditor.editor.execCommand('inserthtml', inHtml)
        this.uploadVideo = false
        this.imgData.imgUrl = ''
      }
    },

    uploadfile() {
      window.document.getElementById(this.flagId + 1).click()
    }

  }
}
</script>

<style>
.preview{
  min-height: 150px;
}
.edui-toolbar.edui-default, .edui-box.edui-button{
  line-height: 1;
}
</style>
